/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-09-15 14:14:23
 * @filename : static/logic/nmm/src/views/upgrade.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){
    require('{component}promptTip/promptTip.css');
    var messageConversationView,cuserInfo,rid,toName,userInfo,bool,histroyBool=true,
        mId = 'messageConversation',reRender = false,menuName = 'messageConversation',
        swipe = require('{component}swipe/zepto.swipe'),
        promptTip = require('{component}promptTip/promptTip'),
        panel = require('{component}panel/zepto.panel'),
        dialog = require('{component}dialog/zepto.dialog'),
        tpl  = require('{view}messageConversation.tpl'),
        tplN = require('{view}userNav.tpl');

    messageConversationView = Backbone.View.extend({

        el: '',

        template: _.template(tpl),
        templateN: _.template(tplN),

        initialize: function () {
            $(window).bind('orientationchange.messageConversation',function(){
                $('#'+mId).find('.messageBox').css('height',this.messageHeight());         
            });
        },

        render: function (obj) {
            if (share.PMSG == null) {
                window.location.href = '#messageList/whole';
                return;
            }
            
            if (!share.checkPermission(true)){return;};

            var arr = obj.val.split('&');
            toName = arr[0];
            rid = arr[1];
            cuserInfo = this.getCuserInfo();
           
            if ($('#'+mId).length < 1) { 
                $('body').append(this.template(lang));      
                share.PMSG.markAllMessageRead(toName);
                this.bindEvt();
                this.setMessageOpt();
                userInfo = share.userInfo();
                bool = false;
                //console.log('init',toName,rid);
                share.PMSG.getArchive(toName,rid,'personal_chat');
                $('#'+mId).find('.messageUser').html(toName);
                $('#'+mId).find('.messageBox').css('height',this.messageHeight());         
                $('#'+mId).find('.messageBox')[0].scrollTop = $('#'+mId).find('.messagehistorylist').height(); 
            } else {
                $('#'+mId).find('.message_loading').hide();
                $('#'+mId).css('display','block');
            }

            share.panel(panel,this.templateN,mId,menuName);   
        
            setTimeout(function() {
                var width =  $('#'+mId).find('.body_all').width();
                 $('#'+mId).find('.message_loading').css('width', width+'px'); 
                 //$('#'+mId).css('overflow-y','hidden');
            },500);

        },
          
        getCuserInfo : function() {
            var obj = share.getObjStorage('messageList');
            for (var i in obj) {
                 if (obj[i].usr_id == rid) {
                     return obj[i];     
                 }
            }
        },

        messageHeight : function() {
            var  dom = $('#'+mId),
                 WH = $(window).height(),
                 headHeight = dom.find('.head').height(),
                 sendHeight = dom.find('.bot_messagesentbox').height();                 
            var messageHeight = WH - headHeight - sendHeight - 15 - 15;
            return messageHeight;
        },

        setMessageOpt : function() {
            share.PMSG.opt.addMessageToChat = this.addMessageToChat;
        },

        addMessageToChat : function(messages,type) {
             
            var dom = $('#'+mId),
                tplM = require('{view}messageConversationLi.tpl'),
                templateM =  _.template(tplM);
            
            messages.selfname = userInfo.username.toLowerCase();
            messages.toName = toName;
            messages.fomatTime = share.formatChatDate(messages.time);
            messages.sysType = typeof(messages.sysType) == 'undefined' ? '' : messages.sysType;
            messages.data = JSON.stringify(messages);
            messages.uid = typeof(messages.id) == 'undefined' ? messages.messagesId : messages.id; 
            messages.defaultImg = seajs.data.vars.resourceUrl+'img/';
            
            //兼容数据格式 
            var pic = '',
                temp = share.getObjStorage(userInfo.usr_id),
                obj = (temp !== null) ? temp : userInfo;

            if (obj.pictures !== undefined && obj.pictures.length > 0) {
                pic = obj.pictures[0].picture;
            }

            dom.find('.message_loading').hide();
           
            if (messages.sender == messages.selfname) {
                messages.icon = pic;
            } else {
                messages.icon = cuserInfo.icon;
            }

     

            if (type) {
               dom.find('.messagehistorylist').find('ul').append(templateM(messages));
               dom.find('.messageBox')[0].scrollTop = dom.find('.messagehistorylist').height(); 
            } else {
               dom.find('.messagehistorylist').find('ul').prepend(templateM(messages));
               if (!bool) {
                   dom.find('.messageBox')[0].scrollTop = dom.find('.messagehistorylist').height(); 
               } else {
                   dom.find('.messageBox')[0].scrollTop = 10; 
               }
               setTimeout(function(){
                   histroyBool = true;
               },1000);
            }

            dom.find('.messagehistorylist').imglazyload({startY : 0,endY: dom.height(),sW:45,sH:45}); 
        },
       
        bindEvt : function() {
            var tthis = this,dom = $('#'+mId);      
            dom.find('.messageBox').on('scroll',function(e){
                if(seajs.moduleUI == 'messageConversation') {
                    if (dom.find('.messageBox')) {
                        var scrollTop = dom.find('.messageBox').scrollTop();
                        dom.find('.messagehistorylist').imglazyload({startY : 0,endY: dom.height(),sW:45,sH:45});
                    }
                }
             });

            dom.on('touchmove',function(e){
                e.stopPropagation();
            }); 


            dom.find('.back').on('tap',function(e){
                e.stopPropagation();
                $('#'+mId).remove();
                window.location.href = '#messageList/whole';
            }); 
           
            var input  = dom.find('.sendBox').find('input');
            input.keypress(function(e){
                 if (e.keyCode == 13) {
                     tthis.sendMessage();   
                     //this.blur();

                 } 
            });

            dom.find('.messageBox').on('tap',function(){
                var input  = dom.find('.sendBox').find('input');
                    input.blur();
            });

   
            dom.find('.sendButton').on('tap',function(){
                tthis.sendMessage(); 
            });

            dom.find('.messagehistorylist').on('singleTap',function(e) {
                var id = $(e.target).closest('.readmore').attr('id');
                if (id) {
                    window.location.href = '#mailDetail/whole/custom'+id;
                } 
            });

            dom.find('.messageUser').on('tap',function(){
                window.location.href = '#userProfile/whole/custom'+rid+'&&'+toName+'&&messageList';
            });

            dom.find('.messagehistorylist').on('singleTap',function(e) {
                var dom = $(e.target).closest('.profile');
                if (dom.length > 0) { 
                    window.location.href = '#userProfile/whole/custom'+rid+'&&'+toName+'&&messageList';
                }
            });

            dom.find('.messageBox').swipe({
                 swipeUp : function(e){ 
                    //console.log('up');
                 },
                 swipeDown : function(e){
                    //console.log('down');
                    if (dom.find('.messageBox')[0].scrollTop == 0 && histroyBool) {
                        bool = true;
                        histroyBool = false;
                        var timepoint = dom.find('.messagehistorylist').find('li').first().find('span').attr('time'),
                            width = dom.find('.body_all').width();
                        dom.find('.message_loading').css('width', width+'px').show();
                        share.PMSG.getArchive(toName, rid ,'personal_chat',timepoint);
                    }
                 } 
            });

        },

        openDialog : function() {
            dialog.open({
                type : 'payDialog',
                dom : $('#'+mId).find('.body_all'),
                cover : true,
                close : true,
                positionRelative : true
            });
        },


        sendMessage : function() {
            /*
            if (share.isGuest()) {
                this.openDialog();
                return;
            } 
            */

            var msg = $('#'+mId).find('.sendBox').find('input').val();
            if ($.trim(msg) == '') {
                promptTip.show({type:'error',text:'You can’t send a blank message.', dom:$('#'+mId).find('.promptTip'),time:2000});
                return;
            }

            var obj = {
                      messageContent : msg,
                      sender : userInfo.username.toLowerCase(),
                      senderId : userInfo.usr_id,
                      receiverId : rid,
                      receiver : toName,
                      message_obj : share.PMSG.constructNewMessage(msg, userInfo.username)
                 };  

           share.PMSG.sendMessage(obj);

            var messages = {
                      type : "chat",
                      time : new Date(),
                   message : obj.messageContent,  
                    sender : userInfo.username.toLowerCase(),
                  uniqueId : obj.message_obj.uniqueId                        
                };
            this.addMessageToChat(messages,true); 

            $('#'+mId).find('.sendBox').find('input').val('');
        }
    });
    module.exports = messageConversationView;
});
